package com.xneure.database;

import com.xneure.database.sql.ValueConvert;
import com.xneure.database.sql.handler.SqlHandler;

public class QueryExpression{
	private StringBuilder column = new StringBuilder();
	private StringBuilder group = new StringBuilder();
	private StringBuilder ordey = new StringBuilder();
	private String sql;

	public QueryExpression(String sql){
		this.sql = sql;
	}

	public void setSql(String sql){
		this.sql = sql;
	}

	public void reset(){
		column.setLength(0);
		ordey.setLength(0);
		group.setLength(0);
	}

	public void resolve(String name,Object value){
		StringBuilder value_ = new StringBuilder();
		if(name.contains("_")){
			String[] tmp = name.split("_");
			ValueConvert convert = SqlHandler.getValueConvert();
			for(int i = 0;i < tmp.length;i++){
				switch(tmp[i]){
					case "g":
						column.append(" > ");
						column.append(convert.sqlValue(value));
						break;
					case "l":
						column.append(" < ");
						column.append(convert.sqlValue(value));
						break;
					case "e":
						column.append(" = ");
						column.append(convert.sqlValue(value));
						break;
					case "n":
						column.append(" is ");
						column.append(convert.sqlValue(value));
						break;
					case "nn":
						column.append(" is null ");
						break;
					case "%like":
						column.append(" like ");
						value_.append(convert.sqlValue(value));
						value_.insert(1,"%");
						column.append(value_);
						break;
					case "like%":
						column.append(" like ");
						value_.append(convert.sqlValue(value));
						value_.insert(value_.length() - 1,"%");
						column.append(value_);
						break;
					case "%like%":
						column.append(" like ");
						value_.append(convert.sqlValue(value));
						value_.insert(1,"%");
						value_.insert(value_.length() - 1,"%");
						column.append(value_);
						break;
					case "and":
						if(column.length() > 5){
							column.append(" AND ");
						}
						break;
					case "not":
						column.append(" NOT ");
						break;
					case "or":
						if(column.length() > 5){
							column.append(" OR ");
						}
						break;
					case "group":
						group.append(name);
						group.append(",");
						break;
					case "desc":
					case "asc":
						ordey.append(name);
						ordey.append(" ");
						ordey.append(tmp[i]);
						ordey.append(",");
						break;
					default:
						column.append(tmp[i]);
						break;
				}
			}
		}
	}

	public String toSql(){
		if(column.length() > 1){
			column.insert(0,sql);
			column.insert(sql.length()," where ");
			if(group.length() > 0){
				group.insert(0," group by ");
				group.setLength(group.length() - 1);
			}
			column.append(group);
			if(ordey.length() > 0){
				ordey.insert(0," ordey by ");
				ordey.setLength(ordey.length() - 1);
			}
			column.append(group);
			return column.toString();
		}else{
			return sql;
		}
	}
}
